package com.aiyige.page.my.wallet;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.page.my.wallet.adapter.WalletSingleDetailsListAdapter;
import com.aiyige.page.my.wallet.model.WalletSingleEntity;
import com.aiyige.page.my.wallet.model.WalletSingleModel;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.TitleLayout;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 单笔明细-（商品销售收入、提现支出、退款手续费支出、买家责任收入、卖家责任收入）
 */
@Route(path = ARouterConfig.WalletSingleDetailsPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class WalletSingleDetailPage extends BaseActivity {


    @BindView(R.id.mainRv)
    RecyclerView mainRv;
    @BindView(R.id.loadingLayout)
    View loadingLayout;
    @BindView(R.id.errorLayout)
    View errorLayout;
    @BindView(R.id.emptyLayout)
    View emptyLayout;

    WalletSingleDetailsListAdapter adapter;

    @Autowired
    String id;
    @BindView(R.id.title_layout)
    TitleLayout titleLayout;
    @BindView(R.id.emptyIv)
    ImageView emptyIv;
    @BindView(R.id.emptyTv)
    TextView emptyTv;
    @BindView(R.id.errorIv)
    ImageView errorIv;
    @BindView(R.id.errorTv)
    TextView errorTv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_wallet_single_details_list);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (TextUtils.isEmpty(id)) {
            ToastX.show(R.string.unknown_error);
            finish();
            return;
        }
        initTitleLayout(getString(R.string.single_detail));
        adapter = new WalletSingleDetailsListAdapter();
        mainRv.setLayoutManager(new LinearLayoutManager(this));
        adapter.bindToRecyclerView(mainRv);
        requestData();
    }

    public void requestData() {
        new RequestDataTask(this, id).execute();
    }

    public void showErrorLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        loadingLayout.setVisibility(View.INVISIBLE);
        emptyLayout.setVisibility(View.INVISIBLE);
    }

    public void showLoadingLayout() {
        errorLayout.setVisibility(View.INVISIBLE);
        loadingLayout.setVisibility(View.VISIBLE);
        emptyLayout.setVisibility(View.INVISIBLE);
    }

    public void showEmptyLayout() {
        errorLayout.setVisibility(View.INVISIBLE);
        loadingLayout.setVisibility(View.INVISIBLE);
        emptyLayout.setVisibility(View.VISIBLE);
    }

    public void hideCoverLayout() {
        errorLayout.setVisibility(View.INVISIBLE);
        loadingLayout.setVisibility(View.INVISIBLE);
        emptyLayout.setVisibility(View.INVISIBLE);
    }

    @OnClick({R.id.errorLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.errorLayout:
                requestData();
                break;
        }
    }


    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        String id = "";
        List<WalletSingleEntity> resultList = new LinkedList<>();

        public RequestDataTask(Activity activity, String id) {
            super(activity);
            this.id = id;
            showLoadingLayout();
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
                showErrorLayout();
            } else {
                if (ListUtil.isEmpty(resultList)) {
                    showEmptyLayout();
                } else {
                    adapter.setNewData(resultList);
                    hideCoverLayout();
                }
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getWalletAggLogsList(id).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<WalletSingleModel> walletSingleModelList = JSON.parseArray(json, WalletSingleModel.class);
                if (!ListUtil.isEmpty(walletSingleModelList)) {
                    resultList = model2entity(walletSingleModelList);
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    private void test() {
        List<WalletSingleEntity> list = new ArrayList<>();
        list.add(WalletSingleEntity.newBuilder().title("订单金额").value("+2608.00").type(WalletSingleEntity.TYPE_KEY_VALUE).build());
        list.add(WalletSingleEntity.newBuilder().title("第三方支付平台手续费").value("-38.00").type(WalletSingleEntity.TYPE_KEY_VALUE).build());
        list.add(WalletSingleEntity.newBuilder().title("退款到账（收入）").value("2345.00").type(WalletSingleEntity.TYPE_INCOME).build());
        list.add(WalletSingleEntity.newBuilder().title("订单编号").value("176235176253716253").type(WalletSingleEntity.TYPE_ORDER_ID).build());
        list.add(WalletSingleEntity.newBuilder().title("订单金额").value("+2608.00").detail("(包含第三方支付平台手续费 ￥2.00)").type(WalletSingleEntity.TYPE_DETAIL).build());
        adapter.addData(list);
    }

    private List<WalletSingleEntity> model2entity(List<WalletSingleModel> list) {
        if (ListUtil.isEmpty(list)) {
            return null;
        }
        List<WalletSingleEntity> entityList = new ArrayList<>();
        WalletSingleEntity entity;
        for (WalletSingleModel model : list) {

            entity = WalletSingleEntity.newBuilder().title(model.getName()).detail(model.getExtra()).value(model.getValue()).build();
            switch (model.getType()) {
                case WalletSingleModel.normal:
                    entity.setType(WalletSingleEntity.TYPE_KEY_VALUE);
                    break;
                case WalletSingleModel.normal_extra:
                    entity.setType(WalletSingleEntity.TYPE_DETAIL);
                    break;
                case WalletSingleModel.normal_grey:
                    entity.setType(WalletSingleEntity.TYPE_GREY_VALUE);
                    break;
                case WalletSingleModel.normal_mark:
                    entity.setType(WalletSingleEntity.TYPE_ORDER_ID);
                    break;
                case WalletSingleModel.normal_RMB:
                    entity.setType(WalletSingleEntity.TYPE_INCOME);
                    break;

            }
            entity.setRole(model.getRole());
            entityList.add(entity);
        }
        return entityList;

    }


}
